OutOfBoundsException Exception

Occurs when code tries to access an array element that doesn't exist.


Notes

An OutOfBoundsException error occurs when your code uses an array index that is out of range. This occurs, for example, if you forget that arrays in REALbasic are zero-based and you make an error when you try to access the last element.


Examples

This example is supposed to display the fonts installed on the user's computer in a ListBox. It generates an OutOfBoundsException because the loop should be from 0 to nFonts-1 rather than from 1 to nFonts. When the loop gets to nFonts, the value of i is out of range and the error occurs.

Dim i, nFonts as Integer
nFonts= FontCount
For i=1 to nFonts //don't do this!
 ListBox1.addrow( Font(i))
Next

If you run this code in a built application, you will see a generic error message when i reaches the value of nFonts.

The application quits when the user accepts this dialog.

You can handle the exception by adding the following code

Dim i, nFonts as Integer
nFonts= FontCount
For i=1 to nFonts //don't do this!
 ListBox1.addrow( Font(i))
Next
Exception err
If err IsA OutOfBoundsException then
  MsgBox "The value: "+ Str(i)+" is out of range!"
end if

:

When this code runs in a built application, the user sees a dialog box that gives the value of the out of range number dialog box.

The application does not quit when the user accepts the dialog box.


See Also

RuntimeException class; Function, Raise, Sub statements; Nil keyword, Exception, Try blocks.